package com.css.zfzx.sjcj.modules.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.zfzx.sjcj.common.RestResultData;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.pojo.*;
import com.css.zfzx.sjcj.modules.service.*;
import com.css.zfzx.sjcj.modules.service.HandlerService;
import com.css.zfzx.sjcj.modules.service.PcProgressFillService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Log4j2
@RestController
@RequestMapping("/pc")
public class HandlerController {
    @Autowired
    HandlerService handlerService;
    @Autowired
    PcProgressFillService pcProgressFillService;
    @Autowired
    PcStatisticsFillService pcStatisticsFillService;

    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;

    @GetMapping("/getDivision")
    public RestResultData getDivision(HttpServletRequest req) {
        String userId = ServerUtil.getUserId(req);
        DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
        String divisionName = mainDept.getDeptName();

        return RestResultData.ok(mainDept);
    }

    @GetMapping("/getMenuInfo")
    public RestResultData getMenuInfo(@RequestParam String taskCode, HttpServletRequest req) {
        List<RespondParams> pcEntities = pcProgressFillService.findByTaskCode(taskCode, req);

        return RestResultData.ok(pcEntities);
    }

    @GetMapping("/getMenuInfos")
    public RestResultData getMenuInfos() {
        RespondParams pcEntities = pcProgressFillService.findAll();

        return RestResultData.ok(pcEntities);
    }

    @PostMapping("/statistics")
    public RestResultData pcDataStatistics(@RequestParam String type, @RequestParam String divisions, @RequestParam String dataType,
                                           @RequestParam String menuIds, @RequestParam String startTime, @RequestParam String endTime) {
        RequestParams requestParams = new RequestParams();
        requestParams.setType(type);
        requestParams.setDivisionList(Arrays.asList(divisions.split(",")));
        requestParams.setDataType(dataType);
        requestParams.setMenuIdList(Arrays.asList(menuIds.split(",")));
        requestParams.setStartTime(startTime);
        requestParams.setEndTime(endTime);
        return RestResultData.ok(handlerService.handlerData(requestParams));
    }


    @PostMapping("/update")
    public RestResultData pcUpdateData(@RequestBody List<UpdateVo> vos, HttpServletRequest req) {
        pcProgressFillService.updatePcProgressFill(vos, req);
        RestResultData restResultData= new RestResultData();
        restResultData.setMessage("操作完成！");
        return RestResultData.ok(restResultData);
    }

    @GetMapping("/queryProgress")
    public RestResultData pcQueryProgress(@RequestParam String taskCode) {
        List<RespondParams> resultList = pcProgressFillService.queryProgressCount(taskCode);
        if (null == resultList){
            return RestResultData.fail("数据查询失败","500");
        }else {
            return RestResultData.ok(resultList);
        }
    }

    @GetMapping("/export")
    public void pcDataExport(HttpServletResponse response, @RequestParam String type, @RequestParam String divisions,
                             @RequestParam String dataType, @RequestParam String menuIds,
                             @RequestParam String startTime, @RequestParam String endTime) {
        RequestParams requestParams = new RequestParams();
        requestParams.setType(type);
        requestParams.setDivisionList(Arrays.asList(divisions.split(",")));
        requestParams.setDataType(dataType);
        requestParams.setMenuIdList(Arrays.asList(menuIds.split(",")));
        requestParams.setStartTime(startTime);
        requestParams.setEndTime(endTime);
        handlerService.handlerExportData(response, requestParams);
    }

    @GetMapping("/findStatistics")
    public RestResponse findStatistics(QueryVo queryVo, HttpServletRequest req) {
        RestResponse response = null;
        String userId = ServerUtil.getUserId(req);
        try{
            int curPage = Integer.valueOf(req.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(req.getParameter(PlatformPageUtils.PAGE_SIZE));
            String sort= req.getParameter("sort");
            String order= req.getParameter("order");
            JSONObject list = pcStatisticsFillService.find(queryVo,userId,curPage,pageSize,sort,order);
            response = RestResponse.succeed(list);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /**
     * 根据附件名称下载附件
     *
     * @param response
     * @param response
     */
    @GetMapping("/attachment-download")
    public void attachmentDownload(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        RestResponse<String> message = null;
        //获取到指定文件
        File file = new File(uploadPath+fileName);
        // 如果文件名存在，则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(DateFormat.getDateInstance().format(new Date())+"-"+fileName, "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                log.info("附件下载成功！");
            } catch (Exception e) {
                log.info("附件下载失败！");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {//对应文件不存在
            log.info("文件不存在");
        }
    }

    @GetMapping("/exportStatistics")
    public void exportStatistics(QueryVo queryVo, HttpServletRequest req,HttpServletResponse resp) {
        String userId = ServerUtil.getUserId(req);
        try{
            pcStatisticsFillService.exportStatistics(queryVo,userId,resp);
        }catch (Exception e){
            String errorMessage = "查询失败!";
            log.error(errorMessage,e);
        }
    }
}
